﻿-- -----------------------------------------------------------------------------
-- AuctionProfit by kunda
-- -----------------------------------------------------------------------------

AuctionProfit = AceLibrary("AceAddon-2.0"):new("AceEvent-2.0", "AceHook-2.1", "AceConsole-2.0", "AceDB-2.0", "FuBarPlugin-2.0")
AuctionProfit:RegisterDB("AuctionProfitDB")

local L = AceLibrary("AceLocale-2.2"):new("AuctionProfit")
local Dewdrop = AceLibrary("Dewdrop-2.0")
local AP_StartCheck
local AP_BabyOneMoreTime									-- prevent multi data save
local AP_sortType = 0											-- data sort type
local AP_sortOrder = 0										-- data sort order: 0 = asc | 1 = desc
local AP_sortData = 0											-- data type: 0 = name | 1 = buys/name(last20) | 2 = profit
local AP_LastXAuctions = 20
local AP_ItemNames = {}										-- table with pure item names from actual server
local AP_ItemIndex = {}										-- table with item index keys from actual server
local AP_ItemCount = 0										-- totalnumber of items from actual server
local AP_NameIndex = {}										-- table with pure names from actual server
local AP_NameCount = 0										-- totalnumber of names from actual server
local AP_ServerName = GetCVar("realmName")
local AP_ServerNameIndex
local AP_color_white = "|cffffffff"				-- sRGB		= { r = 1,			g = 1,			b = 1,			a = 1 }
local AP_color_blue = "|cff6699ff"				-- sRGB		= { r = 0.4,		g = 0.6,		b = 1,			a = 1 }
local AP_color_green = "|cff00b27b"				-- sRGB		= { r = 0.0001,	g = 0.6981,	b = 0.4824,	a = 1 }
local AP_color_yellow = "|cffffff00"			-- sRGB		= { r = 1,			g = 1,			b = 0,			a = 1 }
local AP_color_lightyellow = "|cffffff7f"	-- sRGB		= { r = 1,			g = 1,			b = 0.4981,	a = 1 }
local AP_SearchQuery
local AP_dbnum
local AP_ListData

-- other addons
local AP_isAucCompactUI = false						-- Auctioneer Advanced Compact UI

-- local functions
local AP_HumanMoneyDisplay, AP_nummatrix
local AP_StrReturn, AP_buyerNameReturn, AP_buyerMainDataReturn, AP_buyerSubDataReturn, AP_buyerSubDataCountReturn, AP_buyerSubDataItemIDcheckReturn
local AP_buyerSubDataPartReturn, AP_buyerSubDataPartProfitReturn, AP_buyerSubDataPartBuysReturn, AP_buyerSubDataPartReplaceReturn
local AP_itemNameReturn, AP_itemNameSubDataReturn, AP_itemNameServerCheckReturn
local AP_itemNameSubDataPartReturn, AP_itemNameSubDataPartProfitReturn, AP_itemNameSubDataPartBuysReturn
local AP_itemNameSubDataPartReplaceReturn, AP_lastAuctionsReturn

-- lua functions
local string_format = string.format
local string_gsub = string.gsub
local string_find = string.find
local string_sub = string.sub
local string_len = string.len
local string_match = string.match
local string_lower = string.lower
local tonumber = tonumber
local tostring = tostring

-- default settings
local AP_DefaultSettings = {
	TooltipLineDisplay = 5,
	TooltipItemNameLength = 40,

	PlayerTooltipToggle = true,
	PlayerTooltipOOC = true,
	PlayerTooltipLines = 10,

	AHBrowseTabProfit = true,
	AHTooltipToggle = true,
	AHTooltipLines = 20,
	AHTooltipPosX = -250,
	AHTooltipPosY = 0,
	AHTooltipPosAnchor = "ANCHOR_BOTTOMRIGHT",
			
	APwindowSearchShow = false,
	APwindowToggle = true,
	APwindowTooltipToggle = true,
	APwindowTooltipLines = 30,
	APwindowTooltipPosX = -250,
	APwindowTooltipPosY = -5,
	APwindowTooltipPosAnchor = "ANCHOR_BOTTOMRIGHT",
			
	StartMessage = true
}

-- -----------------------------------------------------------------------------
local options = {
	type = "group",
	args = {
		TooltipLineDisplay = {
			type = "group",
			name = L["Tooltip Line Appearance"],
			desc = L["Tooltip Line Appearance. All Tooltip displays!"],
			order = 10,
			disabled = function()
				if
				AuctionProfit.db.profile.settings.PlayerTooltipToggle or
				AuctionProfit.db.profile.settings.AHTooltipToggle or
				AuctionProfit.db.profile.settings.APwindowTooltipToggle
				then
					return false
				else
					return true
				end
			end,
			args = {
				TooltipLineDisplay1 = {
					type = "toggle",
					name = "name/item : count : profit",
					desc = "name/item : count : profit",
					order = 10.1,
					get = function()
						if AuctionProfit.db.profile.settings.TooltipLineDisplay == 1 then
							return true
						else
							return false
						end
					end,
					set = function()
						AuctionProfit.db.profile.settings.TooltipLineDisplay = 1
					end
				},
				TooltipLineDisplay2 = {
					type = "toggle",
					name = "count : name/item : profit",
					desc = "count : name/item : profit",
					order = 10.2,
					get = function()
						if AuctionProfit.db.profile.settings.TooltipLineDisplay == 2 then
							return true
						else
							return false
						end
					end,
					set = function()
						AuctionProfit.db.profile.settings.TooltipLineDisplay = 2
					end
				},
				TooltipLineDisplay3 = {
					type = "toggle",
					name = "count : profit : name/item",
					desc = "count : profit : name/item",
					order = 10.3,
					get = function()
						if AuctionProfit.db.profile.settings.TooltipLineDisplay == 3 then
							return true
						else
							return false
						end
					end,
					set = function()
						AuctionProfit.db.profile.settings.TooltipLineDisplay = 3
					end
				},
				TooltipLineDisplay4 = {
					type = "toggle",
					name = "profit : name/item : count",
					desc = "profit : name/item : count",
					order = 10.4,
					get = function()
						if AuctionProfit.db.profile.settings.TooltipLineDisplay == 4 then
							return true
						else
							return false
						end
					end,
					set = function()
						AuctionProfit.db.profile.settings.TooltipLineDisplay = 4
					end
				},
				TooltipLineDisplay5 = {
					type = "toggle",
					name = "profit : count : name/item",
					desc = "profit : count : name/item",
					order = 10.5,
					get = function()
						if AuctionProfit.db.profile.settings.TooltipLineDisplay == 5 then
							return true
						else
							return false
						end
					end,
					set = function()
						AuctionProfit.db.profile.settings.TooltipLineDisplay = 5
					end
				},
			},
		},
		Spacer1 = {
			type = "header",
			order = 14
		},
		PlayerHeader = {
			type = "header",
			name = L["Player"],
			order = 15
		},
		PlayerTooltipToggle = {
			type = "toggle",
			name = L["Enable/Disable Tooltip"],
			desc = L["Enable or disable AuctionProfit data in player tooltip."],
			order = 20,
			get = function()
				return AuctionProfit.db.profile.settings.PlayerTooltipToggle
			end,
			set = function()
				AuctionProfit.db.profile.settings.PlayerTooltipToggle = not AuctionProfit.db.profile.settings.PlayerTooltipToggle
				if AuctionProfit:IsHooked(GameTooltip, "OnTooltipSetUnit") and not AuctionProfit.db.profile.settings.PlayerTooltipToggle then
					AuctionProfit:Unhook(GameTooltip, "OnTooltipSetUnit")
				else
					AuctionProfit:HookScript(GameTooltip, "OnTooltipSetUnit", "GameTooltip_OnTooltipSetUnit")
				end
			end
		},
		PlayerTooltipOOC = {
			type = "toggle",
			name = L["Tooltip Out-Of-Combat only"],
			desc = L["Show AuctionProfit data in player tooltip only if you are OOC (Out-Of-Combat)."],
			order = 30,
			disabled = function()
				if AuctionProfit.db.profile.settings.PlayerTooltipToggle then
					return false
				else
					return true
				end
			end,
			get = function()
				return AuctionProfit.db.profile.settings.PlayerTooltipOOC
			end,
			set = function()
				AuctionProfit.db.profile.settings.PlayerTooltipOOC = not AuctionProfit.db.profile.settings.PlayerTooltipOOC
			end
		},
		PlayerTooltipLines = {
			type = "range",
			name = L["Tooltip Lines"],
			desc = L["Maximum Lines in Player Tooltip.\n0 = Only Profit"],
			order = 40,
			disabled = function()
				if AuctionProfit.db.profile.settings.PlayerTooltipToggle then
					return false
				else
					return true
				end
			end,
			min = 0,
			max = 40,
			step = 1,
			get = function() return AuctionProfit.db.profile.settings.PlayerTooltipLines end,
			set = function(v) AuctionProfit.db.profile.settings.PlayerTooltipLines = v end
		},
		Spacer2 = {
			type = "header",
			order = 44
		},
		AHHeader = {
			type = "header",
			name = L["Auction House"],
			order = 45
		},
		AHBrowseTabProfit = {
			type = "toggle",
			name = L["Show Profit in Auctions"],
			desc = L["Enable or disable the display of your profit under the name of the seller in Auction House Tab 'Auction Browse'.\n\nIf you are at the Auction House while changing this option: This is active after the next auction update (new search / scroll up or down)."],
			order = 46,
			disabled = function()
				if IsAddOnLoaded("Auc-Advanced") and AucAdvanced.Settings.GetSetting("util.compactui.activated") then
					return true
				else
					return false
				end
			end,
			get = function()
				return AuctionProfit.db.profile.settings.AHBrowseTabProfit
			end,
			set = function()
				AuctionProfit.db.profile.settings.AHBrowseTabProfit = not AuctionProfit.db.profile.settings.AHBrowseTabProfit
				if not AuctionProfit.db.profile.settings.AHBrowseTabProfit then
					if AP_AHBrowseTabFrame1 then
						for i=1, NUM_BROWSE_TO_DISPLAY do
							getglobal("AP_AHBrowseTabFrame"..i):Hide()
						end
					end
					if AuctionProfit:IsHooked("GetAuctionItemInfo") then
						AuctionProfit:Unhook("GetAuctionItemInfo")
					end
				end
				if AuctionProfit.db.profile.settings.AHBrowseTabProfit then
					if not AuctionProfit:IsHooked("GetAuctionItemInfo") then
						AuctionProfit:SecureHook("GetAuctionItemInfo")
					end
				end
			end,
		},
		AHTooltipToggle = {
			type = "toggle",
			name = L["Enable/Disable Tooltip"],
			desc = L["Enable or disable AuctionProfit data in Auction House tooltip."],
			order = 50,
			disabled = function()
				if IsAddOnLoaded("Auc-Advanced") and AucAdvanced.Settings.GetSetting("util.compactui.activated") then
					return true
				else
					return false
				end
			end,
			get = function()
				return AuctionProfit.db.profile.settings.AHTooltipToggle
			end,
			set = function()
				AuctionProfit.db.profile.settings.AHTooltipToggle = not AuctionProfit.db.profile.settings.AHTooltipToggle
			end
		},
		AHTooltipLines = {
			type = "range",
			name = L["Tooltip Lines"],
			desc = L["Maximum Lines in Auction House Tooltip.\n0 = Only Profit"],
			order = 60,
			disabled = function()
				if IsAddOnLoaded("Auc-Advanced") and AucAdvanced.Settings.GetSetting("util.compactui.activated") then
					return true
				else
					if AuctionProfit.db.profile.settings.AHTooltipToggle then
						return false
					else
						return true
					end
				end
			end,
			min = 0,
			max = 40,
			step = 1,
			get = function() return AuctionProfit.db.profile.settings.AHTooltipLines end,
			set = function(v) AuctionProfit.db.profile.settings.AHTooltipLines = v end
		},
		AHTooltipPos = {
			type = "group",
			name = L["Tooltip Position"],
			desc = L["Tooltip Position for Auction House."],
			order = 70,
			disabled = function()
				if IsAddOnLoaded("Auc-Advanced") and AucAdvanced.Settings.GetSetting("util.compactui.activated") then
					return true
				else
					if AuctionProfit.db.profile.settings.AHTooltipToggle then
						return false
					else
						return true
					end
				end
			end,
			args = {
				AHTooltipPosAnchor = {
					type = "group",
					name = L["Anchor"],
					desc = L["Don't forget Pos X and Pos Y!"],
					order = 70.1,
					args = {
						AHTooltipPosAnchor1 = {
							type = "toggle",
							name = L["BottomRight Tooltip corner -> anchored to TopRight Line corner"],
							desc = L["BottomRight Tooltip corner -> anchored to TopRight Line corner"],
							order = 70.11,
							get = function()
								if AuctionProfit.db.profile.settings.AHTooltipPosAnchor == "ANCHOR_TOPRIGHT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.AHTooltipPosAnchor = "ANCHOR_TOPRIGHT"
							end,
						},
						AHTooltipPosAnchor2 = {
							type = "toggle",
							name = L["BottomLeft Tooltip corner -> anchored to TopRight Line corner"],
							desc = L["BottomLeft Tooltip corner -> anchored to TopRight Line corner"],
							order = 70.12,
							get = function()
								if AuctionProfit.db.profile.settings.AHTooltipPosAnchor == "ANCHOR_RIGHT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.AHTooltipPosAnchor = "ANCHOR_RIGHT"
							end,
						},
						AHTooltipPosAnchor3 = {
							type = "toggle",
							name = L["TopLeft Tooltip corner -> anchored to BottomRight Line corner"],
							desc = L["TopLeft Tooltip corner -> anchored to BottomRight Line corner"],
							order = 70.13,
							get = function()
								if AuctionProfit.db.profile.settings.AHTooltipPosAnchor == "ANCHOR_BOTTOMRIGHT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.AHTooltipPosAnchor = "ANCHOR_BOTTOMRIGHT"
							end,
						},
						AHTooltipPosAnchor4 = {
							type = "toggle",
							name = L["BottomLeft Tooltip corner -> anchored to TopLeft Line corner"],
							desc = L["BottomLeft Tooltip corner -> anchored to TopLeft Line corner"],
							order = 70.14,
							get = function()
								if AuctionProfit.db.profile.settings.AHTooltipPosAnchor == "ANCHOR_TOPLEFT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.AHTooltipPosAnchor = "ANCHOR_TOPLEFT"
							end,
						},
						AHTooltipPosAnchor5 = {
							type = "toggle",
							name = L["BottomRight Tooltip corner -> anchored to TopLeft Line corner"],
							desc = L["BottomRight Tooltip corner -> anchored to TopLeft Line corner"],
							order = 70.15,
							get = function()
								if AuctionProfit.db.profile.settings.AHTooltipPosAnchor == "ANCHOR_LEFT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.AHTooltipPosAnchor = "ANCHOR_LEFT"
							end,
						},
						AHTooltipPosAnchor6 = {
							type = "toggle",
							name = L["TopRight Tooltip corner -> anchored to BottomLeft Line corner"],
							desc = L["TopRight Tooltip corner -> anchored to BottomLeft Line corner"],
							order = 70.16,
							get = function()
								if AuctionProfit.db.profile.settings.AHTooltipPosAnchor == "ANCHOR_BOTTOMLEFT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.AHTooltipPosAnchor = "ANCHOR_BOTTOMLEFT"
							end,
						},
					},
				},
				AHTooltipPosX = {
					type = "range",
					name = L["Pos X"],
					desc = L["Pos X"],
					order = 70.2,
					min = -600,
					max = 600,
					step = 1,
					bigstep = 50,
					get = function() return AuctionProfit.db.profile.settings.AHTooltipPosX end,
					set = function(v) AuctionProfit.db.profile.settings.AHTooltipPosX = v end
				},
				AHTooltipPosY = {
					type = "range",
					name = L["Pos Y"],
					desc = L["Pos Y"],
					order = 70.3,
					min = -50,
					max = 50,
					step = 1,
					bigstep = 5,
					get = function() return AuctionProfit.db.profile.settings.AHTooltipPosY end,
					set = function(v) AuctionProfit.db.profile.settings.AHTooltipPosY = v end
				},
			},
		},
		Spacer3 = {
			type = "header",
			order = 74
		},
		APwindowHeader = {
			type = "header",
			name = L["AuctionProfit Window"],
			order = 75
		},
		APwindowToggle = {
			type = "toggle",
			name = L["Auto show AuctionProfit Window"],
			desc = L["Automatically show AuctionProfit Window when new data from an invoice auction house mail is saved."],
			order = 80,
			get = function()
				return AuctionProfit.db.profile.settings.APwindowToggle
			end,
			set = function()
				AuctionProfit.db.profile.settings.APwindowToggle = not AuctionProfit.db.profile.settings.APwindowToggle
			end
		},
		APwindowTooltipToggle = {
			type = "toggle",
			name = L["Enable/Disable Tooltip"],
			desc = L["Enable or disable AuctionProfit data in AuctionProfit Window tooltip."],
			order = 90,
			get = function()
				return AuctionProfit.db.profile.settings.APwindowTooltipToggle
			end,
			set = function()
				AuctionProfit.db.profile.settings.APwindowTooltipToggle = not AuctionProfit.db.profile.settings.APwindowTooltipToggle
			end
		},
		APwindowTooltipLines = {
			type = "range",
			name = L["Tooltip Lines"],
			desc = L["Maximum Lines in AuctionProfit Window Tooltip."],
			order = 100,
			disabled = function()
				if AuctionProfit.db.profile.settings.APwindowTooltipToggle then
					return false
				else
					return true
				end
			end,
			min = 1,
			max = 40,
			step = 1,
			get = function() return AuctionProfit.db.profile.settings.APwindowTooltipLines end,
			set = function(v) AuctionProfit.db.profile.settings.APwindowTooltipLines = v end
		},
		APwindowTooltipPos = {
			type = "group",
			name = L["Tooltip Position"],
			desc = L["Tooltip Position for AuctionProfit Window."],
			order = 110,
			disabled = function()
				if AuctionProfit.db.profile.settings.APwindowTooltipToggle then
					return false
				else
					return true
				end
			end,
			args = {
				APwindowTooltipPosAnchor = {
					type = "group",
					name = L["Anchor"],
					desc = L["Don't forget Pos X and Pos Y!"],
					order = 110.1,
					args = {
						APwindowTooltipPosAnchor1 = {
							type = "toggle",
							name = L["BottomRight Tooltip corner -> anchored to TopRight Line corner"],
							desc = L["BottomRight Tooltip corner -> anchored to TopRight Line corner"],
							order = 110.11,
							get = function()
								if AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor == "ANCHOR_TOPRIGHT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor = "ANCHOR_TOPRIGHT"
							end,
						},
						APwindowTooltipPosAnchor2 = {
							type = "toggle",
							name = L["BottomLeft Tooltip corner -> anchored to TopRight Line corner"],
							desc = L["BottomLeft Tooltip corner -> anchored to TopRight Line corner"],
							order = 110.12,
							get = function()
								if AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor == "ANCHOR_RIGHT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor = "ANCHOR_RIGHT"
							end,
						},
						APwindowTooltipPosAnchor3 = {
							type = "toggle",
							name = L["TopLeft Tooltip corner -> anchored to BottomRight Line corner"],
							desc = L["TopLeft Tooltip corner -> anchored to BottomRight Line corner"],
							order = 110.13,
							get = function()
								if AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor == "ANCHOR_BOTTOMRIGHT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor = "ANCHOR_BOTTOMRIGHT"
							end,
						},
						APwindowTooltipPosAnchor4 = {
							type = "toggle",
							name = L["BottomLeft Tooltip corner -> anchored to TopLeft Line corner"],
							desc = L["BottomLeft Tooltip corner -> anchored to TopLeft Line corner"],
							order = 110.14,
							get = function()
								if AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor == "ANCHOR_TOPLEFT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor = "ANCHOR_TOPLEFT"
							end,
						},
						APwindowTooltipPosAnchor5 = {
							type = "toggle",
							name = L["BottomRight Tooltip corner -> anchored to TopLeft Line corner"],
							desc = L["BottomRight Tooltip corner -> anchored to TopLeft Line corner"],
							order = 110.15,
							get = function()
								if AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor == "ANCHOR_LEFT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor = "ANCHOR_LEFT"
							end,
						},
						APwindowTooltipPosAnchor6 = {
							type = "toggle",
							name = L["TopRight Tooltip corner -> anchored to BottomLeft Line corner"],
							desc = L["TopRight Tooltip corner -> anchored to BottomLeft Line corner"],
							order = 110.16,
							get = function()
								if AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor == "ANCHOR_BOTTOMLEFT" then
									return true
								else
									return false
								end
							end,
							set = function()
								AuctionProfit.db.profile.settings.APwindowTooltipPosAnchor = "ANCHOR_BOTTOMLEFT"
							end,
						},
					},
				},
				APwindowTooltipPosX = {
					type = "range",
					name = L["Pos X"],
					desc = L["Pos X"],
					order = 110.2,
					min = -600,
					max = 600,
					step = 1,
					bigstep = 50,
					get = function() return AuctionProfit.db.profile.settings.APwindowTooltipPosX end,
					set = function(v) AuctionProfit.db.profile.settings.APwindowTooltipPosX = v end
				},
				APwindowTooltipPosY = {
					type = "range",
					name = L["Pos Y"],
					desc = L["Pos Y"],
					order = 110.3,
					min = -50,
					max = 50,
					step = 1,
					bigstep = 5,
					get = function() return AuctionProfit.db.profile.settings.APwindowTooltipPosY end,
					set = function(v) AuctionProfit.db.profile.settings.APwindowTooltipPosY = v end
				},
			},
		},
		Spacer4 = {
			type = "header",
			order = 114
		},
		General = {
			type = "header",
			name = L["General"],
			order = 115
		},
		StartMessage = {
			type = "toggle",
			name = L["Enable/Disable Login WARNING"],
			desc = L["Enable or disable Login WARNING Message."],
			order = 120,
			get = function()
				return AuctionProfit.db.profile.settings.StartMessage
			end,
			set = function()
				AuctionProfit.db.profile.settings.StartMessage = not AuctionProfit.db.profile.settings.StartMessage
			end
		},
		ResetToDefaultSettings = {
			type = "execute",
			name = L["Reset to DEFAULT settings"],
			desc = L["Reset to DEFAULT settings. Only settings! - NO invoice auction house mail data will be deleted!"],
			order = 130,
			func = function()
				for k,v in pairs(AP_DefaultSettings) do
					AuctionProfit.db.profile.settings[k] = v
				end
			end
		},
	},
}
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
AuctionProfit.hasIcon = true
AuctionProfit.hasNoText = true
AuctionProfit.title = "AuctionProfit"
AuctionProfit.defaultPosition = "LEFT"
AuctionProfit.hideMenuTitle = true
AuctionProfit.cannotDetachTooltip = true
AuctionProfit.cannotHideText = false
AuctionProfit.hasNoColor = true
AuctionProfit.OnMenuRequest = options
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
--function AuctionProfit:debug(text)
--	if DEFAULT_CHAT_FRAME then
--		DEFAULT_CHAT_FRAME:AddMessage(AP_color_lightyellow.."DEBUG AuctionProfit: |r"..text)
--	end
--end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:OnInitialize()
	if APserver == nil				then APserver = {}				end
	if APbuyer == nil					then APbuyer = {}					end
	if APitemName == nil			then APitemName = {}			end
	if APlastAuctions == nil	then APlastAuctions = {}	end
	self:RegisterDefaults("profile", {settings = AP_DefaultSettings})
	self:RegisterChatCommand({"/ap","/auctionprofit"}, options)
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:OnEnable()
	if self.db.profile.settings.StartMessage and DEFAULT_CHAT_FRAME then
		DEFAULT_CHAT_FRAME:AddMessage(AP_color_lightyellow.."AuctionProfit: "..L["Login WARNING"])
		DEFAULT_CHAT_FRAME:AddMessage(AP_color_lightyellow.."AuctionProfit: |r"..L["1.) DO NOT USE addons that auto collect money from your mails!"])
		DEFAULT_CHAT_FRAME:AddMessage(AP_color_lightyellow.."AuctionProfit: |r"..L["2.) Click on an invoice auction house mail to OPEN it! Click the money!"])
		DEFAULT_CHAT_FRAME:AddMessage(AP_color_lightyellow.."AuctionProfit: |r"..L["3.) Read readme.txt!"])
		DEFAULT_CHAT_FRAME:AddMessage(AP_color_lightyellow.."AuctionProfit: |r"..L["To disable this message type '/ap StartMessage' or use option in the Dewdrop menu (Minimap or FuBar)."])
	end
	tinsert(UISpecialFrames,"APFrame")
	self:SecureHook("TakeInboxMoney")
	self:SecureHook("InboxFrame_OnClick", "OopsIDidItAgain")
	self:SecureHook("OpenMailFrame_OnHide", "OopsIDidItAgain")
	if self.db.profile.settings.PlayerTooltipToggle then
		self:HookScript(GameTooltip, "OnTooltipSetUnit", "GameTooltip_OnTooltipSetUnit")
	end
	-- Auctioneer Compact UI check
	if IsAddOnLoaded("Auc-Advanced") and AucAdvanced.Settings.GetSetting("util.compactui.activated") then
		AP_isAucCompactUI = true
	end
	-- NO Auctioneer Compact UI support at the moment:
	if not AP_isAucCompactUI then
		self:RegisterEvent("AUCTION_HOUSE_SHOW")
		self:RegisterEvent("AUCTION_HOUSE_CLOSED")
	end
	self:DataUpdate()
	self:FrameInit(0)
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:AUCTION_HOUSE_SHOW()
	if not AP_AHBrowseTabFrame1 then
		for i=1, NUM_BROWSE_TO_DISPLAY do
			local framename = "AP_AHBrowseTabFrame"..i
			local textname = "AP_AHBrowseTabFrameText"..i
			local texturename = "AP_AHBrowseTabFrameTexture"..i
			local parent = getglobal("BrowseButton"..i)
			local point = getglobal("BrowseButton"..i.."HighBidder")
			local frame = CreateFrame("Frame", framename, parent)
			frame:ClearAllPoints()
			frame:SetPoint("BOTTOM", point, "BOTTOM", 0, -2)
			frame:SetWidth(100)
			frame:SetHeight(12)
			frame:Hide()
			local texture = frame:CreateTexture(texturename, "DIALOG")
			texture:SetPoint("CENTER", framename, "CENTER", 0, 0)
			texture:SetTexture(0, 0, 0, 0.3)
			texture:SetWidth(100)
			texture:SetHeight(12)
			local text = frame:CreateFontString(textname, "DIALOG", "GameFontNormalSmall")
			text:SetPoint("CENTER", framename, "CENTER", 0, 2)
		end
	end
	if self.db.profile.settings.AHBrowseTabProfit and not self:IsHooked("GetAuctionItemInfo") then
		self:SecureHook("GetAuctionItemInfo")
	end
	for i=1, NUM_BROWSE_TO_DISPLAY do
		local obj = getglobal("BrowseButton"..i)
		self:HookScript(obj, "OnEnter", "GameTooltip_AuctionOnEnter")
		self:HookScript(obj, "OnLeave", "GameTooltip_AuctionOnLeave")
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:AUCTION_HOUSE_CLOSED()
	if self.db.profile.settings.AHBrowseTabProfit and self:IsHooked("GetAuctionItemInfo") then
		self:Unhook("GetAuctionItemInfo")
	end
	for i=1, NUM_BROWSE_TO_DISPLAY do
		local obj = getglobal("BrowseButton"..i)
		if obj then
			if self:IsHooked(obj, "OnEnter") then
				self:Unhook(obj, "OnEnter")
			end
			if self:IsHooked(obj, "OnLeave") then
				self:Unhook(obj, "OnLeave")
			end
		end
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:GetAuctionItemInfo(type, pos)
	if type == "list" then
		if self:IsHooked("GetAuctionItemInfo") then
			self:Unhook("GetAuctionItemInfo")
		end
	
		local owner = select(12, GetAuctionItemInfo("list", pos))

		if owner then
			local profit
			for i=1, AP_NameCount do
				if AP_NameIndex[i] == owner then
					local buyerData = AP_buyerMainDataReturn(APbuyer[AP_ServerNameIndex][i])
					profit = AP_HumanMoneyDisplay( tonumber( AP_StrReturn(buyerData,2) ) )
					break
				end
			end

			local index = pos - BrowseScrollFrame.offset -- FauxScrollFrame_GetOffset(BrowseScrollFrame)

			 -- Auctioneer classic bugfix ompf - cleanup START
			if index > NUM_BROWSE_TO_DISPLAY then
				index = NUM_BROWSE_TO_DISPLAY --self:debug("Auctioneer classic bug ompf") --BUGcheck
			end
			if index < 1 then
				index = 1 --self:debug("Auctioneer classic bug ompf") --BUGcheck
			end
			 -- Auctioneer classic bugfix ompf - cleanup END

			local frame = getglobal("AP_AHBrowseTabFrame"..index)
			if profit then
				--self:debug("NUM_="..NUM_BROWSE_TO_DISPLAY.." i="..index.." - "..BrowseScrollFrame.offset.." - "..pos.." - "..owner.." "..profit) --BUGcheck
				local text = getglobal("AP_AHBrowseTabFrameText"..index)
				local texture = getglobal("AP_AHBrowseTabFrameTexture"..index)
				text:SetText(profit)
				local w = text:GetStringWidth()
				frame:SetWidth(w+2)
				texture:SetWidth(w+2)
				frame:Show()
			else
				frame:Hide()
			end
		end
		if not self:IsHooked("GetAuctionItemInfo") then
			self:SecureHook("GetAuctionItemInfo")
		end
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:GameTooltip_AuctionOnEnter(this, ...)
	self.hooks[this].OnEnter(this, ...)
	if not self.db.profile.settings.AHTooltipToggle then return end
	local id = this:GetID() + FauxScrollFrame_GetOffset(BrowseScrollFrame)
	local t = self.db.profile.settings

	if t.AHBrowseTabProfit then
		if self:IsHooked("GetAuctionItemInfo") then
			self:Unhook("GetAuctionItemInfo")
		end
	end
	local owner = select(12, GetAuctionItemInfo("list", id))
	if t.AHBrowseTabProfit then
		if not self:IsHooked("GetAuctionItemInfo") then
			self:SecureHook("GetAuctionItemInfo")
		end
	end

	if owner then
		local TooltipText = self:TooltipSummary(owner, "AH")
		if TooltipText then
			GameTooltip:SetOwner(this, t.AHTooltipPosAnchor, t.AHTooltipPosX, t.AHTooltipPosY)
			GameTooltip:SetText(owner.."\n\n"..TooltipText)
			GameTooltip:Show()
		end
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:GameTooltip_AuctionOnLeave(this, ...)
	self.hooks[this].OnLeave(this, ...)
	if not self.db.profile.settings.AHTooltipToggle then return end
	GameTooltip:Hide()
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:GameTooltip_OnTooltipSetUnit(this, ...)
	self.hooks[this].OnTooltipSetUnit(this, ...)
	if not AP_ServerNameIndex then return end
	if self.db.profile.settings.PlayerTooltipOOC and UnitAffectingCombat("player") then return end
	if UnitIsPlayer("mouseover") then
		local PlayerName = this:GetUnit()
		if not PlayerName then return end
		local PlayerRealm = select(2, UnitName("mouseover"))
		--if PlayerRealm == nil then self:debug("PlayerRealm = nil") else self:debug(PlayerRealm) end --BUGcheck
		if PlayerRealm then return end
		local TooltipText = self:TooltipSummary(PlayerName, "Player")
		if TooltipText then
			GameTooltip:AddLine(TooltipText, 1, 1, 1)
			GameTooltip:Show()
		end
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:DataUpdate()
	if APserver and #APserver > 0 then
		for i=1, #APserver do
			if APserver[i] == AP_ServerName then
				AP_ServerNameIndex = i
				break
			end
		end
	end
	if AP_ServerNameIndex then
		AP_NameCount = #APbuyer[AP_ServerNameIndex]
		for i=1, AP_NameCount do
			local data = APbuyer[AP_ServerNameIndex][i]
			local pos = string_find(data, ":", 1)
			local str = string_sub(data, 1, pos-1)
			AP_NameIndex[i] = str
		end
		self:DataCheck()
		self:StatusLineTxt()
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:DataCheck()
	if AP_StartCheck then return end
	local x = 1
	for i=1, #APitemName do
		if AP_itemNameServerCheckReturn(APitemName[i],AP_ServerNameIndex) then
			AP_ItemIndex[x] = i
			AP_ItemNames[x] = AP_itemNameReturn(APitemName[i])
			x = x + 1
		end
	end
	AP_ItemCount = #AP_ItemIndex
	AP_StartCheck = 1
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:FrameToggle(FrameName)
	local frame = getglobal(FrameName)
	if frame:IsShown() then
		frame:Hide()
	else
		self:MainFramePos()
		frame:Show()
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:MainFramePos()
	local settings = AuctionProfit.db.profile.settings
	if settings.relP then
		APFrame:ClearAllPoints()
		APFrame:SetPoint(settings.relP, settings.posX, settings.posY)
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:MainFrameHide()
	AP_ListData = nil
	Dewdrop:Close()
	PlaySound("igQuestListClose")
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:MainFrameShow()
	PlaySound("igQuestListOpen")
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:CreateOptionsMenu()
	Dewdrop:Open(APFrame_headline_ButtonOptions,
		'point', function(parent)
			return "TOPLEFT","BOTTOMLEFT"
		end,
		'dontHook', true,
		'children', function()
			Dewdrop:FeedAceOptionsTable(options)
		end
		)
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:OnClick()
	self:FillList(AP_sortType, AP_sortOrder, AP_sortData)
	self:FrameToggle("APFrame")
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:OopsIDidItAgain()
	AP_BabyOneMoreTime = nil
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:TakeInboxMoney(idx)
	if not idx then return end
	if AP_BabyOneMoreTime then return end
	AP_BabyOneMoreTime = true
	--local x1 = GetTime() --BUGcheck
	
	local invoiceType, itemName, playerName, bid, buyout, deposit, consignment = GetInboxInvoiceInfo(idx)

	if playerName and invoiceType == "seller" then
		
		local AP_profit
		if bid == buyout	then AP_profit = buyout - consignment end	-- buyout
		if bid < buyout		then AP_profit = bid - consignment end		-- bid
		if buyout == 0		then AP_profit = bid - consignment end		-- bid (no buyout)
		
		if not AP_profit then return end
		if not itemName then return end

		----------------------------------------------------------------------------------------------------------
		-- APserver save / update START ----------
		local APserverNum = #APserver
		local AP_ServerNameIDX = nil
		for i=1, APserverNum do
			if APserver[i] == AP_ServerName then
				AP_ServerNameIDX = i
				break
			end
		end
		if AP_ServerNameIDX == nil and APserverNum > 0 then
			local newServerNum = APserverNum+1
			APserver[newServerNum] = AP_ServerName
			AP_ServerNameIDX = newServerNum
		end
		if AP_ServerNameIDX == nil then
			APserver[1] = AP_ServerName
			AP_ServerNameIDX = 1
		end
		-- APserver save / update END ----------
		----------------------------------------------------------------------------------------------------------

		----------------------------------------------------------------------------------------------------------
		-- APitemName new entry / update START ----------
		local APitemNameNum = #APitemName
		local AP_itemNameIDX = nil
		-- APitemName update with entries and with itemName START ----------
		for i=1, APitemNameNum do
			if AP_itemNameReturn(APitemName[i]) == itemName then
				AP_itemNameIDX = i
				-- check if item has server entry (AP_ServerNameIDX)
				-- yes(1) = update | no(else 0) = add new entry
				if AP_itemNameServerCheckReturn(APitemName[i],AP_ServerNameIDX) then
					local AP_itemNameIDX_profit = tonumber( AP_itemNameSubDataPartProfitReturn(APitemName[i],AP_ServerNameIDX) )
					local AP_itemNameIDX_buys = tonumber( AP_itemNameSubDataPartBuysReturn(APitemName[i],AP_ServerNameIDX) )
					AP_itemNameIDX_profit = AP_itemNameIDX_profit + AP_profit
					AP_itemNameIDX_buys = AP_itemNameIDX_buys + 1
					local AP_itemNameIDX_subData = tostring(AP_ServerNameIDX).."-"..tostring(AP_itemNameIDX_profit).."-"..tostring(AP_itemNameIDX_buys)
					local AP_itemNameIDX_subDataOLD = AP_itemNameSubDataPartReturn(APitemName[i],AP_ServerNameIDX)
					-- replace ... search for subDataOLD and replace with subData
					local AP_itemNameIDX_subData_replace = AP_itemNameSubDataPartReplaceReturn(APitemName[i],AP_itemNameIDX_subDataOLD,AP_itemNameIDX_subData)
					APitemName[i] = itemName.."#"..AP_itemNameIDX_subData_replace
				else
					APitemName[i] = APitemName[i]..":"..tostring(AP_ServerNameIDX).."-"..tostring(AP_profit).."-1"
					-- update AP_ItemIndex
					AP_ItemCount = AP_ItemCount + 1
					AP_ItemIndex[AP_ItemCount] = AP_itemNameIDX
					AP_ItemNames[AP_ItemCount] = itemName
					-- update AP_ItemIndex
				end
				break
			end
		end
		-- APitemName update with entries and with itemName END ----------
		-- APitemName update with entries but not with itemName START ----------
		if AP_itemNameIDX == nil and APitemNameNum > 0 then
			APitemName[APitemNameNum+1] = itemName.."#"..tostring(AP_ServerNameIDX).."-"..tostring(AP_profit).."-1"
			AP_itemNameIDX = APitemNameNum+1
			-- update AP_ItemIndex
			AP_ItemCount = AP_ItemCount + 1
			AP_ItemIndex[AP_ItemCount] = AP_itemNameIDX
			AP_ItemNames[AP_ItemCount] = itemName
			-- update AP_ItemIndex
		end
		-- APitemName update with entries but not with itemName END ----------
		-- APitemName update with no entries START
		if AP_itemNameIDX == nil then
			APitemName[1] = itemName.."#"..tostring(AP_ServerNameIDX).."-"..tostring(AP_profit).."-1"
			AP_itemNameIDX = 1
			-- update AP_ItemIndex
			AP_ItemCount = 1
			AP_ItemIndex = {}
			AP_ItemIndex[AP_ItemCount] = AP_itemNameIDX
			AP_ItemNames[AP_ItemCount] = itemName
			-- update AP_ItemIndex
		end
		-- APitemName update with no entries END ----------
		-- APitemName new entry / update END ----------
		----------------------------------------------------------------------------------------------------------

		----------------------------------------------------------------------------------------------------------
		-- APbuyer new entry / update START ----------
		if APbuyer[AP_ServerNameIDX] == nil
			then APbuyer[AP_ServerNameIDX] = {}
		end
		local APbuyerNum = #APbuyer[AP_ServerNameIDX]
		local AP_buyerNameIDX = nil
		-- APbuyer update with entries and with playerName START ----------
		for i=1, APbuyerNum do
			--local AP_buyer = APbuyer[AP_ServerNameIDX][i]
			--local AP_buyerName = AP_buyerNameReturn(AP_buyer)
			if AP_NameIndex[i] == playerName then -- AP_NameIndex keys are equal to APbuyer[AP_ServerNameIDX]
			--if AP_buyerName == playerName then
				AP_buyerNameIDX = i
				local AP_buyer = APbuyer[AP_ServerNameIDX][i]
				
				-- update APbuyer MainData
				local AP_buyerNameIDX_maindata = AP_buyerMainDataReturn(AP_buyer)
				local AP_buyerNameIDX_profit = tonumber( AP_StrReturn(AP_buyerNameIDX_maindata ,2) )
				local AP_buyerNameIDX_buys = tonumber( AP_StrReturn(AP_buyerNameIDX_maindata ,3) )
				AP_buyerNameIDX_profit = AP_buyerNameIDX_profit + AP_profit
				AP_buyerNameIDX_buys = AP_buyerNameIDX_buys + 1
				AP_buyerNameIDX_mainData = playerName..":"..tostring(AP_buyerNameIDX_profit)..":"..tostring(AP_buyerNameIDX_buys)
				-- update APbuyer MainData

				-- update APbuyer SubData
				-- check if buyer has itemName: yes(1) = update | no(else 0) = add new entry
				if AP_buyerSubDataItemIDcheckReturn(AP_buyer,AP_itemNameIDX) then
					local AP_buyerNameIDX_subData_profit = AP_profit + tonumber(AP_buyerSubDataPartProfitReturn(AP_buyer,AP_itemNameIDX))
					local AP_buyerNameIDX_subData_buys = tonumber(AP_buyerSubDataPartBuysReturn(AP_buyer,AP_itemNameIDX)) + 1
					local AP_buyerNameIDX_subData = tostring(AP_itemNameIDX).."-"..tostring(AP_buyerNameIDX_subData_profit).."-"..tostring(AP_buyerNameIDX_subData_buys)
					local AP_buyerNameIDX_subDataOLD = AP_buyerSubDataPartReturn(AP_buyer,AP_itemNameIDX)
					-- replace ... search for subDataOLD and replace with subData
					local AP_buyerNameIDX_subData_replace = AP_buyerSubDataPartReplaceReturn(AP_buyer,AP_buyerNameIDX_subDataOLD,AP_buyerNameIDX_subData)
					APbuyer[AP_ServerNameIDX][i] = AP_buyerNameIDX_mainData.."#"..AP_buyerNameIDX_subData_replace
				else
					local AP_buyerNameIDX_subData = tostring(AP_itemNameIDX).."-"..tostring(AP_profit).."-1"
					local AP_buyerNameIDX_subDataOLD = AP_buyerSubDataReturn(AP_buyer)
					APbuyer[AP_ServerNameIDX][i] = AP_buyerNameIDX_mainData.."#"..AP_buyerNameIDX_subDataOLD..":"..AP_buyerNameIDX_subData
				end
				-- update APbuyer SubData
				break
			end
		end
		-- APbuyer update with entries and with playerName END ----------
		-- APbuyer update with entries but not with playerName START ----------
		if AP_buyerNameIDX == nil and APbuyerNum > 0 then
			APbuyer[AP_ServerNameIDX][APbuyerNum+1] = playerName..":"..tostring(AP_profit)..":1#"..tostring(AP_itemNameIDX).."-"..tostring(AP_profit).."-1"
			AP_buyerNameIDX = APbuyerNum+1
		end
		-- APbuyer update with entries but not with playerName END ----------
		-- APbuyer update with no entries START ----------
		if AP_buyerNameIDX == nil then
			APbuyer[AP_ServerNameIDX][1] = playerName..":"..tostring(AP_profit)..":1#"..tostring(AP_itemNameIDX).."-"..tostring(AP_profit).."-1"
			AP_buyerNameIDX = 1
		end
		-- APbuyer update with no entries END ----------
		-- APbuyer new entry / update START ----------
		----------------------------------------------------------------------------------------------------------

		----------------------------------------------------------------------------------------------------------
		-- APlastAuctions save / update START ----------
		if APlastAuctions[AP_ServerNameIDX] == nil then
			APlastAuctions[AP_ServerNameIDX] = {}
		end
		local APlastAuctionsNum = #APlastAuctions[AP_ServerNameIDX]
		local AP_lastAuctionsIDX = nil
		if APlastAuctionsNum == AP_LastXAuctions then
			for i=1, (APlastAuctionsNum-1) do
				APlastAuctions[AP_ServerNameIDX][i] = APlastAuctions[AP_ServerNameIDX][i+1]
			end
			AP_lastAuctionsIDX = AP_LastXAuctions
		else
			AP_lastAuctionsIDX = APlastAuctionsNum+1
		end
		if AP_lastAuctionsIDX == nil then
			AP_lastAuctionsIDX = 1
		end
		local xdate = date("%y%m%d %H%M")
		APlastAuctions[AP_ServerNameIDX][AP_lastAuctionsIDX] = xdate.."#"..tostring(AP_itemNameIDX)..":"..tostring(AP_profit)..":"..tostring(AP_buyerNameIDX)
		-- APlastAuctions save / update END ----------
		----------------------------------------------------------------------------------------------------------

		self:Print(itemName.." | "..AP_color_blue..L["Buyer"]..": "..AP_color_white..playerName.." | "..AP_color_blue..L["Profit"]..": "..AP_HumanMoneyDisplay(AP_profit))
		self:DataUpdate()
		--local x2 = GetTime() self:debug("time TakeInBoxMoney1: "..x2-x1) --BUGcheck
		if self.db.profile.settings.APwindowToggle then
			self:DisplayMode(2)
			self:MainFramePos()
			APFrame:Show()
		end
	end

	--local x3 = GetTime() self:debug("time TakeInBoxMoney2: "..x3-x1) --BUGcheck

end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:OnVerticalScroll()
	local itemHeight = 12
	local scrollbar = getglobal(this:GetName().."ScrollBar")
	scrollbar:SetValue(arg1)
	this.offset = floor((arg1 / itemHeight) + 0.5)
	self:FillList()
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:FillList(sort, order, data)
	if not AP_ServerNameIndex then return end

	local AP_showtableNumSize = 20

	if data == 0 then AP_dbnum = AP_NameCount end
	if data == 1 then AP_dbnum = AP_ItemCount end
	if data == 2 then AP_dbnum = #APlastAuctions[AP_ServerNameIndex] end

 	if sort and order and data then
		self:SortTable(sort, order, data)
	end

	if #AP_ListData ~= AP_dbnum then
		AP_dbnum = #AP_ListData
	end

	if AP_dbnum and AP_dbnum < AP_showtableNumSize then
		for i=1, AP_showtableNumSize do
			getglobal("APList"..i):Hide()
		end
		AP_showtableNumSize = AP_dbnum
	end

	FauxScrollFrame_Update(APFrame_ScrollFrame, AP_dbnum, AP_showtableNumSize, 12)

	if AP_dbnum <= 20 then
		APFrame_ScrollFrame:Hide()
	else
		APFrame_ScrollFrame:Show()
	end

	local j = 1
	local sliderPos = APFrame_ScrollFrame.offset -- FauxScrollFrame_GetOffset(APFrame_ScrollFrame)
	for i=sliderPos+1, sliderPos+AP_showtableNumSize do
		if sliderPos < AP_dbnum then
			getglobal("APList"..j.."Name"):SetText( AP_StrReturn(AP_ListData[i], 1) )
			getglobal("APList"..j.."Buys"):SetText( AP_StrReturn(AP_ListData[i], 3) )
			getglobal("APList"..j.."Profit"):SetText( AP_HumanMoneyDisplay( tonumber(AP_StrReturn(AP_ListData[i], 2)) )  )
			getglobal("APList"..j):Show()
			j = j + 1
		end
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:SortTable(sort, order, data)
	-- self:debug("sort="..sort.." | order="..order.." | data="..data) -- BUGcheck
	--local x1 = GetTime() --BUGcheck
	-- arrows
	for i=1, 3 do
		local ArrowG
		if i == 1 then ArrowG = getglobal("APBrowseSortNameArrowArrow") end		--default sort = 0
		if i == 2 then ArrowG = getglobal("APBrowseSortBuysArrowArrow") end		--default sort = 1
		if i == 3 then ArrowG = getglobal("APBrowseSortProfitArrowArrow") end	--default sort = 1
		if (sort+1) == i then
			if (i==2 or i==3) then
				if order == 1 then ArrowG:SetTexCoord(0.5625, 0, 1, 0) end
				if order == 0 then ArrowG:SetTexCoord(0, 0.5625, 0, 1) end
			else
				if order == 1 then ArrowG:SetTexCoord(0.5625, 0, 1, 0) end
				if order == 0 then ArrowG:SetTexCoord(0, 0.5625, 0, 1) end
			end
		else
			ArrowG:SetTexCoord(0, 0, 0, 0)
		end		
		if data == 2 then
			ArrowG:SetTexCoord(0, 0, 0, 0)
		end
	end
	-- arrows

	-- sort by name START -------------------------------
	if sort == 0 then
		AP_sortType = 0
		if (data == 0) then AP_dbnum = AP_NameCount end
		if (data == 1) then AP_dbnum = AP_ItemCount end
		if (data == 2) then AP_dbnum = #APlastAuctions[AP_ServerNameIndex] end
		
		AP_ListData = {}
		local ii = 1
		for i = 1, AP_dbnum do
			if (data == 0) then
				if AP_SearchQuery then
					local str = AP_buyerMainDataReturn(APbuyer[AP_ServerNameIndex][i])
					if string_find(string_lower(str),string_lower(AP_SearchQuery),1,true) then
						AP_ListData[ii] = str
						ii = ii + 1
					end
				else
					AP_ListData[i] = AP_buyerMainDataReturn(APbuyer[AP_ServerNameIndex][i])
				end
				AP_sortData = 0
			end
			if (data == 1) then
				local ItemData = APitemName[AP_ItemIndex[i]]
				if AP_SearchQuery then
					if string_find(string_lower(ItemData),string_lower(AP_SearchQuery),1,true) then
						AP_ListData[ii] = AP_itemNameReturn(ItemData)..":"..AP_itemNameSubDataPartProfitReturn(ItemData,AP_ServerNameIndex)..":"..AP_itemNameSubDataPartBuysReturn(ItemData,AP_ServerNameIndex)
						ii = ii + 1
					end
				else
					AP_ListData[i] = AP_itemNameReturn(ItemData)..":"..AP_itemNameSubDataPartProfitReturn(ItemData,AP_ServerNameIndex)..":"..AP_itemNameSubDataPartBuysReturn(ItemData,AP_ServerNameIndex)
				end
				AP_sortData = 1
			end
			if (data == 2) then
				AP_ListData[(AP_dbnum-i+1)] = AP_lastAuctionsReturn(APlastAuctions[AP_ServerNameIndex][i],AP_ServerNameIndex)
				AP_sortData = 2
			end
		end

		if (data == 2) then return end
		
		if (order == 0) then
			table.sort(AP_ListData, function(a,b) return a<b end)
			AP_sortOrder = 0
		end
		if (order == 1) then
			table.sort(AP_ListData, function(a,b) return a>b end)
			AP_sortOrder = 1
		end
	end
	-- sort by name END -------------------------------

	-- sort by buys START -------------------------------
	if sort == 1 then
		AP_sortType = 1
		if (data == 0) then AP_dbnum = AP_NameCount end
		if (data == 1) then AP_dbnum = AP_ItemCount end
		if (data == 2) then AP_dbnum = #APlastAuctions[AP_ServerNameIndex] end
		
		AP_ListData = {}
		local AP_ListData1 = {}
		local AP_ListData2 = {}
		for i = 1, AP_dbnum do
			if (data == 0) then
				local MainData = AP_buyerMainDataReturn(APbuyer[AP_ServerNameIndex][i])
				AP_ListData1[i] = tonumber(AP_StrReturn(MainData,3)) -- buys
				AP_ListData2[i] = tonumber(AP_StrReturn(MainData,2)) -- profit
				AP_sortData = 0
			end
			if (data == 1) then
				local ItemData = APitemName[AP_ItemIndex[i]]
				AP_ListData1[i] = tonumber(AP_itemNameSubDataPartBuysReturn(ItemData,AP_ServerNameIndex)) -- buys
				AP_ListData2[i] = tonumber(AP_itemNameSubDataPartProfitReturn(ItemData,AP_ServerNameIndex)) -- profit
				AP_sortData = 1
			end
			if (data == 2) then
				AP_ListData[(AP_dbnum-i+1)] = AP_lastAuctionsReturn(APlastAuctions[AP_ServerNameIndex][i],AP_ServerNameIndex)
				AP_sortData = 2
			end
		end
		
		if (data == 2) then return end
		
		table.sort(AP_ListData1, function(a,b) return a>b end)
		table.sort(AP_ListData2, function(a,b) return a>b end)

		local AP_ListData1_xl = string_len(tostring(AP_ListData1[1]))
		local AP_ListData2_xl = string_len(tostring(AP_ListData2[1]))
		
		local ii = 1
		for i = 1, AP_dbnum do
			if (data == 0) then
				local Buyer = APbuyer[AP_ServerNameIndex][i]
				local BuyerMainData = AP_buyerMainDataReturn(Buyer)
				if AP_SearchQuery then
					local str = AP_nummatrix(AP_StrReturn(BuyerMainData,3),AP_ListData1_xl)..AP_nummatrix(AP_StrReturn(BuyerMainData,2),AP_ListData2_xl)..Buyer
					local chk = AP_StrReturn(BuyerMainData,3)..AP_StrReturn(BuyerMainData,2)..Buyer
					if string_find(string_lower(chk),string_lower(AP_SearchQuery),1,true) then
						AP_ListData[ii] = str
						ii = ii + 1
					end
				else
					AP_ListData[i] = AP_nummatrix(AP_StrReturn(BuyerMainData,3),AP_ListData1_xl)..AP_nummatrix(AP_StrReturn(BuyerMainData,2),AP_ListData2_xl)..Buyer
				end
			end
			if (data == 1) then
				local item = AP_ItemIndex[i]
				local ItemData = APitemName[item]
				if AP_SearchQuery then
					local str = AP_nummatrix(AP_itemNameSubDataPartBuysReturn(ItemData,AP_ServerNameIndex),AP_ListData1_xl)..AP_nummatrix(AP_itemNameSubDataPartProfitReturn(ItemData,AP_ServerNameIndex),AP_ListData2_xl)..ItemData
					local chk = AP_itemNameSubDataPartBuysReturn(ItemData,AP_ServerNameIndex)..AP_itemNameSubDataPartProfitReturn(ItemData,AP_ServerNameIndex)..ItemData
					if string_find(string_lower(chk),string_lower(AP_SearchQuery),1,true) then
						AP_ListData[ii] = str
						ii = ii + 1
					end
				else
					AP_ListData[i] = AP_nummatrix(AP_itemNameSubDataPartBuysReturn(ItemData,AP_ServerNameIndex),AP_ListData1_xl)..AP_nummatrix(AP_itemNameSubDataPartProfitReturn(ItemData,AP_ServerNameIndex),AP_ListData2_xl)..ItemData
				end
			end
		end
		
		if (order == 0) then
			table.sort(AP_ListData, function(a,b) return a>b end)
			AP_sortOrder = 0
		end
		if (order == 1) then
			table.sort(AP_ListData, function(a,b) return a<b end)
			AP_sortOrder = 1
		end
		
		for i = 1, #AP_ListData do
			if (data == 0) then
				AP_ListData[i] = AP_buyerMainDataReturn(string_sub(AP_ListData[i],(AP_ListData1_xl+AP_ListData2_xl+1)))
			end
			if (data == 1) then
				AP_ListData[i] = string_sub(AP_itemNameReturn(AP_ListData[i])..":"..AP_itemNameSubDataPartProfitReturn(AP_ListData[i],AP_ServerNameIndex)..":"..AP_itemNameSubDataPartBuysReturn(AP_ListData[i],AP_ServerNameIndex),(AP_ListData1_xl+AP_ListData2_xl+1))
			end
		end
		AP_ListData1 = nil
		AP_ListData2 = nil
	end
	-- sort by buys END -------------------------------

	-- sort by profit START -------------------------------
	if sort == 2 then
		AP_sortType = 2
		if (data == 0) then AP_dbnum = AP_NameCount end
		if (data == 1) then AP_dbnum = AP_ItemCount end
		if (data == 2) then AP_dbnum = #APlastAuctions[AP_ServerNameIndex] end

		AP_ListData = {}
		local AP_ListData1 = {}
		local AP_ListData2 = {}
		for i = 1, AP_dbnum do
			if (data == 0) then
				local MainData = AP_buyerMainDataReturn(APbuyer[AP_ServerNameIndex][i])
				AP_ListData1[i] = tonumber(AP_StrReturn(MainData,3)) -- buys
				AP_ListData2[i] = tonumber(AP_StrReturn(MainData,2)) -- profit
				AP_sortData = 0
			end
			if (data == 1) then
				local ItemData = APitemName[AP_ItemIndex[i]]
				AP_ListData1[i] = tonumber(AP_itemNameSubDataPartBuysReturn(ItemData,AP_ServerNameIndex)) -- buys
				AP_ListData2[i] = tonumber(AP_itemNameSubDataPartProfitReturn(ItemData,AP_ServerNameIndex)) -- profit
				AP_sortData = 1
			end
			if (data == 2) then
				AP_ListData[(AP_dbnum-i+1)] = AP_lastAuctionsReturn(APlastAuctions[AP_ServerNameIndex][i],AP_ServerNameIndex)
				AP_sortData = 2
			end
		end

		if (data == 2) then return end

		table.sort(AP_ListData1, function(a,b) return a>b end)
		table.sort(AP_ListData2, function(a,b) return a>b end)

		local AP_ListData1_xl = string_len(tostring(AP_ListData1[1]))
		local AP_ListData2_xl = string_len(tostring(AP_ListData2[1]))

		local ii = 1
		for i = 1, AP_dbnum do
			if (data == 0) then
				local Buyer = APbuyer[AP_ServerNameIndex][i]
				local BuyerMainData = AP_buyerMainDataReturn(Buyer)
				if AP_SearchQuery then
					local str = AP_nummatrix(AP_StrReturn(BuyerMainData,2),AP_ListData2_xl)..AP_nummatrix(AP_StrReturn(BuyerMainData,3),AP_ListData1_xl)..Buyer
					local chk = AP_StrReturn(BuyerMainData,2)..AP_StrReturn(BuyerMainData,3)..Buyer
					if string_find(string_lower(chk),string_lower(AP_SearchQuery),1,true) then
						AP_ListData[ii] = str
						ii = ii + 1
					end
				else
					AP_ListData[i] = AP_nummatrix(AP_StrReturn(BuyerMainData,2),AP_ListData2_xl)..AP_nummatrix(AP_StrReturn(BuyerMainData,3),AP_ListData1_xl)..Buyer
				end
			end
			if (data == 1) then
				local item = AP_ItemIndex[i]
				local ItemData = APitemName[item]
				if AP_SearchQuery then
					local str = AP_nummatrix(AP_itemNameSubDataPartProfitReturn(ItemData,AP_ServerNameIndex),AP_ListData2_xl)..AP_nummatrix(AP_itemNameSubDataPartBuysReturn(ItemData,AP_ServerNameIndex),AP_ListData1_xl)..ItemData
					local chk = AP_itemNameSubDataPartProfitReturn(ItemData,AP_ServerNameIndex)..AP_itemNameSubDataPartBuysReturn(ItemData,AP_ServerNameIndex)..ItemData
					if string_find(string_lower(chk),string_lower(AP_SearchQuery),1,true) then
						AP_ListData[ii] = str
						ii = ii + 1
					end
				else
					AP_ListData[i] = AP_nummatrix(AP_itemNameSubDataPartProfitReturn(ItemData,AP_ServerNameIndex),AP_ListData2_xl)..AP_nummatrix(AP_itemNameSubDataPartBuysReturn(ItemData,AP_ServerNameIndex),AP_ListData1_xl)..ItemData
				end
			end
		end

		if (order == 0) then
			table.sort(AP_ListData, function(a,b) return a>b end)
			AP_sortOrder = 0
		end
		if (order == 1) then
			table.sort(AP_ListData, function(a,b) return a<b end)
			AP_sortOrder = 1
		end

		for i = 1, #AP_ListData do
			if (data == 0) then
				AP_ListData[i] = AP_buyerMainDataReturn(string_sub(AP_ListData[i],(AP_ListData1_xl+AP_ListData2_xl+1)))
			end
			if (data == 1) then
				AP_ListData[i] = string_sub(AP_itemNameReturn(AP_ListData[i])..":"..AP_itemNameSubDataPartProfitReturn(AP_ListData[i],AP_ServerNameIndex)..":"..AP_itemNameSubDataPartBuysReturn(AP_ListData[i],AP_ServerNameIndex),(AP_ListData1_xl+AP_ListData2_xl+1))
			end
		end
		AP_ListData1 = nil
		AP_ListData2 = nil
	end
	-- sort by profit END -------------------------------
	--local x2 = GetTime() self:debug("SortTable: "..x2-x1) --BUGcheck
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:FrameInit(num, start)
	--self:debug("Frame Init: num="..num) --BUGcheck
	--local x1 = GetTime() --BUGcheck
	local button
	local width

	button = getglobal("APFrame_headline_ButtonName")
	button:SetText(L["Name"])
	width = tonumber(button:GetTextWidth())+20
	button:SetWidth(width)

	button = getglobal("APFrame_headline_ButtonItem")
	button:SetText(L["Items"])
	width = tonumber(button:GetTextWidth())+20
	button:SetWidth(width)

	button = getglobal("APFrame_headline_ButtonLastAuctions")
	button:SetText(string_format(L["Last %s Auctions"],AP_LastXAuctions))
	width = tonumber(button:GetTextWidth())+20
	button:SetWidth(width)
	
	button = getglobal("APFrame_headline_ButtonOptions")
	button:SetText(L["Options"])
	width = tonumber(button:GetTextWidth())+20
	button:SetWidth(width)

	button = getglobal("APFrame_searchBox_ClearButton")
	button:SetText(L["Clear"])
	width = tonumber(button:GetTextWidth())+20
	button:SetWidth(width)

	button = getglobal("APFrame_searchBox_SearchText")
	button:SetText(L["search:"])

	-- first time check ompf
	if AP_ServerNameIndex then
		--self:debug("old user") --BUGcheck
		APFrame_headline_ButtonName:Enable()
		APFrame_headline_ButtonItem:Enable()
		APFrame_headline_ButtonLastAuctions:Enable()
		APFrame_headline_ButtonSearch:Enable()
		APFrame_ListView:Show()
		APFrame_sort:Show()
		APFrame_StatusLine:ClearAllPoints()
		APFrame_StatusLine:SetPoint("TOPLEFT",APFrame_ListView,"BOTTOMLEFT",0,4)
		if self.db.profile.settings.APwindowSearchShow then
			self:SearchFrameShow()
		else
			self:SearchFrameHide()
		end
	else
		--self:debug("first time") --BUGcheck
		APFrame_headline_ButtonName:Disable()
		APFrame_headline_ButtonItem:Disable()
		APFrame_headline_ButtonLastAuctions:Disable()
		APFrame_headline_ButtonSearch:Disable()
		APFrame_ListView:Hide()
		APFrame_sort:Hide()
		APFrame_StatusLine:ClearAllPoints()
		APFrame_StatusLine:SetPoint("TOPLEFT",APFrame_headline,"BOTTOMLEFT",0,4)
		APFrame_StatusLineTxt:SetText(L["No Data!"])
		return
	end

	if num == 0 then
		local col1 = 90
		local col1width = 110
		local col2 = 200
		local col2width = 90
		local col3 = 290
		local col3width = 100
		APFrame_headline_ButtonName:SetTextFontObject("GameFontBlack")
		APFrame_headline_ButtonName:Disable()
		APFrame_headline_ButtonNameNormal:SetTexture(0.8, 0.6, 0, 1)
		APFrame_headline_ButtonItem:SetTextFontObject("GameFontNormal")
		APFrame_headline_ButtonItem:Enable()
		APFrame_headline_ButtonItemNormal:SetTexture(1, 1, 1, 0)
		APFrame_headline_ButtonLastAuctions:SetTextFontObject("GameFontNormal")
		APFrame_headline_ButtonLastAuctions:Enable()
		APFrame_headline_ButtonLastAuctionsNormal:SetTexture(1, 1, 1, 0)
		
		APFrame_searchAlignFrame:Show()
		
		APBrowseSortName:Enable()
		APBrowseSortBuys:Enable()
		APBrowseSortProfit:Enable()
		APBrowseSortNameText:SetText(L["Name"])
		APBrowseSortNameText:ClearAllPoints()
		APBrowseSortNameText:SetPoint("LEFT",0,0)
		APBrowseSortNameArrow:ClearAllPoints()
		APBrowseSortNameArrow:SetPoint("LEFT","APBrowseSortNameText","RIGHT",3,0)
		APBrowseSortName:SetWidth(col1width)
		APBrowseSortName:SetPoint("LEFT","APFrame_sort","LEFT",col1,0)
		APBrowseSortBuysText:SetText(L["Auctions"])
		APBrowseSortBuysText:ClearAllPoints()
		APBrowseSortBuysText:SetPoint("CENTER",0,0)
		APBrowseSortBuysArrow:ClearAllPoints()
		APBrowseSortBuysArrow:SetPoint("LEFT","APBrowseSortBuysText","RIGHT",3,0)
		APBrowseSortBuys:SetWidth(col2width)
		APBrowseSortBuys:SetPoint("LEFT","APFrame_sort","LEFT",col2,0)
		APBrowseSortProfitText:SetText(L["Profit"])
		APBrowseSortProfitText:ClearAllPoints()
		APBrowseSortProfitText:SetPoint("RIGHT",0,0)
		APBrowseSortProfitArrow:ClearAllPoints()
		APBrowseSortProfitArrow:SetPoint("RIGHT","APBrowseSortProfitText","LEFT",-3,0)
		APBrowseSortProfit:SetWidth(col3width)
		APBrowseSortProfit:SetPoint("LEFT","APFrame_sort","LEFT",col3,0)
		for i=1, #APlastAuctions[AP_ServerNameIndex] do
			local calc = ((12*i*(-1))-2)
			local n = getglobal("APList"..i.."Name")
			local b = getglobal("APList"..i.."Buys")
			local p = getglobal("APList"..i.."Profit")
			n:SetWidth(col1width)
			n:SetPoint("LEFT", "APFrame_ListView", "TOPLEFT", col1, calc)
			n:SetTextColor(1, 1, 0, 1) -- yellow

			b:SetWidth(col2width)
			b:SetPoint("LEFT", "APFrame_ListView", "TOPLEFT", col2, calc)
			b:SetTextColor(1, 1, 1, 1) -- white
			b:SetJustifyH("CENTER")

			p:SetWidth(col3width)
			p:SetPoint("LEFT", "APFrame_ListView", "TOPLEFT", col3, calc)
		end
	end
	if num == 1 then
		local col1 = 10
		local col1width = 270
		local col2 = 280
		local col2width = 90
		local col3 = 370
		local col3width = 100
		APFrame_headline_ButtonName:SetTextFontObject("GameFontNormal")
		APFrame_headline_ButtonName:Enable()
		APFrame_headline_ButtonNameNormal:SetTexture(1, 1, 1, 0)
		APFrame_headline_ButtonItem:SetTextFontObject("GameFontBlack")
		APFrame_headline_ButtonItem:Disable()
		APFrame_headline_ButtonItemNormal:SetTexture(0.8, 0.6, 0, 1)
		APFrame_headline_ButtonLastAuctions:SetTextFontObject("GameFontNormal")
		APFrame_headline_ButtonLastAuctions:Enable()
		APFrame_headline_ButtonLastAuctionsNormal:SetTexture(1, 1, 1, 0)

		APFrame_searchAlignFrame:Show()

		APBrowseSortName:Enable()
		APBrowseSortBuys:Enable()
		APBrowseSortProfit:Enable()
		APBrowseSortNameText:SetText(L["Items"])
		APBrowseSortNameText:ClearAllPoints()
		APBrowseSortNameText:SetPoint("LEFT",0,0)
		APBrowseSortNameArrow:ClearAllPoints()
		APBrowseSortNameArrow:SetPoint("LEFT","APBrowseSortNameText","RIGHT",3,0)
		APBrowseSortName:SetWidth(col1width)
		APBrowseSortName:SetPoint("LEFT","APFrame_sort","LEFT",col1,0)
		APBrowseSortBuysText:SetText(L["Auctions"])
		APBrowseSortBuysText:ClearAllPoints()
		APBrowseSortBuysText:SetPoint("CENTER",0,0)
		APBrowseSortBuysArrow:ClearAllPoints()
		APBrowseSortBuysArrow:SetPoint("LEFT","APBrowseSortBuysText","RIGHT",3,0)
		APBrowseSortBuys:SetWidth(col2width)
		APBrowseSortBuys:SetPoint("LEFT","APFrame_sort","LEFT",col2,0)
		APBrowseSortProfitText:SetText(L["Profit"])
		APBrowseSortProfitText:ClearAllPoints()
		APBrowseSortProfitText:SetPoint("RIGHT",0,0)
		APBrowseSortProfitArrow:ClearAllPoints()
		APBrowseSortProfitArrow:SetPoint("RIGHT","APBrowseSortProfitText","LEFT",-3,0)
		APBrowseSortProfit:SetWidth(col3width)
		APBrowseSortProfit:SetPoint("LEFT","APFrame_sort","LEFT",col3,0)
		for i=1, #APlastAuctions[AP_ServerNameIndex] do
			local calc = ((12*i*(-1))-2)
			local n = getglobal("APList"..i.."Name")
			local b = getglobal("APList"..i.."Buys")
			local p = getglobal("APList"..i.."Profit")
			n:SetWidth(col1width)
			n:SetPoint("LEFT", "APFrame_ListView", "TOPLEFT", col1, calc)
			n:SetTextColor(0.0001, 0.6981, 0.4824, 1) -- green

			b:SetWidth(col2width)
			b:SetPoint("LEFT", "APFrame_ListView", "TOPLEFT", col2, calc)
			b:SetTextColor(1, 1, 1, 1) -- white
			b:SetJustifyH("CENTER")

			p:SetWidth(col3width)
			p:SetPoint("LEFT", "APFrame_ListView", "TOPLEFT", col3, calc)
		end
	end
	if num == 2 then
		local col1 = 10
		local col1width = 250
		local col2 = 260
		local col2width = 110
		local col3 = 370
		local col3width = 100
		APFrame_headline_ButtonName:SetTextFontObject("GameFontNormal")
		APFrame_headline_ButtonName:Enable()
		APFrame_headline_ButtonNameNormal:SetTexture(1, 1, 1, 0)
		APFrame_headline_ButtonItem:SetTextFontObject("GameFontNormal")
		APFrame_headline_ButtonItem:Enable()
		APFrame_headline_ButtonItemNormal:SetTexture(1, 1, 1, 0)
		APFrame_headline_ButtonLastAuctions:SetTextFontObject("GameFontBlack")
		APFrame_headline_ButtonLastAuctions:Disable()
		APFrame_headline_ButtonLastAuctionsNormal:SetTexture(0.8, 0.6, 0, 1)

		APFrame_searchAlignFrame:Hide()

		APBrowseSortName:Disable()
		APBrowseSortBuys:Disable()
		APBrowseSortProfit:Disable()
		APBrowseSortNameText:SetText(L["Items"])
		APBrowseSortNameText:ClearAllPoints()
		APBrowseSortNameText:SetPoint("LEFT",0,0)
		--APBrowseSortNameArrow:ClearAllPoints()
		--APBrowseSortNameArrow:SetPoint("LEFT","APBrowseSortNameText","RIGHT",3,0)
		APBrowseSortName:SetWidth(col1width)
		APBrowseSortName:SetPoint("LEFT","APFrame_sort","LEFT",col1,0)
		APBrowseSortBuysText:SetText(L["Name"])
		APBrowseSortBuysText:ClearAllPoints()
		APBrowseSortBuysText:SetPoint("LEFT",0,0)
		--APBrowseSortBuysArrow:ClearAllPoints()
		--APBrowseSortBuysArrow:SetPoint("LEFT","APBrowseSortBuysText","RIGHT",3,0)
		APBrowseSortBuys:SetWidth(col2width)
		APBrowseSortBuys:SetPoint("LEFT","APFrame_sort","LEFT",col2,0)
		APBrowseSortProfitText:SetText(L["Profit"])
		APBrowseSortProfitText:ClearAllPoints()
		APBrowseSortProfitText:SetPoint("RIGHT",0,0)
		--APBrowseSortProfitArrow:ClearAllPoints()
		--APBrowseSortProfitArrow:SetPoint("RIGHT","APBrowseSortProfitText","LEFT",-3,0)
		APBrowseSortProfit:SetWidth(col3width)
		APBrowseSortProfit:SetPoint("LEFT","APFrame_sort","LEFT",col3,0)
		for i=1, #APlastAuctions[AP_ServerNameIndex] do
			local calc = ((12*i*(-1))-2)
			local n = getglobal("APList"..i.."Name")
			local b = getglobal("APList"..i.."Buys")
			local p = getglobal("APList"..i.."Profit")
			n:SetWidth(col1width)
			n:SetPoint("LEFT", "APFrame_ListView", "TOPLEFT", col1, calc)
			n:SetTextColor(0.0001, 0.6981, 0.4824, 1) -- green

			b:SetWidth(col2width)
			b:SetPoint("LEFT", "APFrame_ListView", "TOPLEFT", col2, calc)
			b:SetTextColor(1, 1, 0, 1) -- yellow
			b:SetJustifyH("LEFT")

			p:SetWidth(col3width)
			p:SetPoint("LEFT", "APFrame_ListView", "TOPLEFT", col3, calc)
		end
	end
	--local x2 = GetTime() self:debug("switch: "..x2-x1) --BUGcheck
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:DisplayMode(num)
	if not AP_ServerNameIndex then return end
	AP_sortData = num
	self:FrameInit(num)
	self:FillList(AP_sortType, AP_sortOrder, AP_sortData)
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:TableSortOrder1()
	if AP_sortType == 0 then
		if AP_sortOrder == 0 then self:FillList(0, 1, AP_sortData) return end
		if AP_sortOrder == 1 then self:FillList(0, 0, AP_sortData) return end
	else
		self:FillList(0, 0, AP_sortData) return
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:TableSortOrder2()
	if AP_sortType == 1 then
		if AP_sortOrder == 0 then self:FillList(1, 1, AP_sortData) return end
		if AP_sortOrder == 1 then self:FillList(1, 0, AP_sortData) return end
	else
		self:FillList(1, 0, AP_sortData) return
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:TableSortOrder3()
	if AP_sortType == 2 then
		if AP_sortOrder == 0 then self:FillList(2, 1, AP_sortData) return end
		if AP_sortOrder == 1 then self:FillList(2, 0, AP_sortData) return end
	else
		self:FillList(2, 0, AP_sortData) return
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:StatusLineTxt()
	local ItemCount = 0
	local ProfitCount = 0
	local AuctionCount = 0
	for i=1, AP_NameCount do
		local buyer = APbuyer[AP_ServerNameIndex][i]
		local auctions = AP_StrReturn(AP_buyerMainDataReturn(buyer),3)
		AuctionCount = AuctionCount + auctions
	end
	for i=1, #APitemName do
		if AP_itemNameServerCheckReturn(APitemName[i],AP_ServerNameIndex) then
			ItemCount = ItemCount + 1
			ProfitCount = ProfitCount + tonumber(AP_itemNameSubDataPartProfitReturn(APitemName[i],AP_ServerNameIndex))
		end
	end
	local txt = AP_color_blue..L["Server"]..": "..AP_color_white..APserver[AP_ServerNameIndex]
	txt = txt.." - "..AP_color_blue..L["Profit"]..": "..AP_HumanMoneyDisplay(ProfitCount).."\n"
	txt = txt..AP_color_blue..L["Auctions"]..": "..AP_color_white..AuctionCount
	txt = txt.." - "..AP_color_blue..L["Buyer"]..": "..AP_color_white..AP_NameCount
	txt = txt.." - "..AP_color_blue..L["Items"]..": "..AP_color_white..ItemCount

	APFrame_StatusLineTxt:SetText(txt)
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:SearchFrameToggle()
	if APFrame_search:IsShown() then
		self:SearchFrameHide()
		self:DisplayMode(AP_sortData)
	else
		self:SearchFrameShow()
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:SearchFrameHide()
	AP_SearchQuery = nil
	APFrame_searchBox:SetText("")
	APFrame_search:Hide()
	APFrame_sort:SetPoint("TOPLEFT", "APFrame_headline", "BOTTOMLEFT", 0, 4)
	self.db.profile.settings.APwindowSearchShow = false
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:SearchFrameShow()
	APFrame_search:Show()
	APFrame_sort:SetPoint("TOPLEFT", "APFrame_search", "BOTTOMLEFT", 0, 4)
	self.db.profile.settings.APwindowSearchShow = true
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:Search()
	AP_SearchQuery = APFrame_searchBox:GetText()
	self:DisplayMode(AP_sortData)
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:SaveFramePos()
	local point, relativeTo, relativePoint, x, y = APFrame:GetPoint()
	self.db.profile.settings.posX = x
	self.db.profile.settings.posY = y
	self.db.profile.settings.relP = relativePoint
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:LineOnEnter(name)
	if not AP_ServerNameIndex then return end
	--self:debug(AP_sortData) -- BUGcheck
	--local x1 = GetTime() --BUGcheck
	if not self.db.profile.settings.APwindowTooltipToggle then return end
	local t = self.db.profile.settings
	if AP_sortData == 0 then
		local PlayerName = getglobal(name.."Name"):GetText()
		local TooltipText = AuctionProfit:TooltipSummary(PlayerName, "APwindow")
		if TooltipText then
			GameTooltip:SetOwner(this, t.APwindowTooltipPosAnchor, t.APwindowTooltipPosX, t.APwindowTooltipPosY)
			GameTooltip:SetText(AP_color_yellow..PlayerName.."\n\n"..TooltipText)
			GameTooltip:Show()
		end
	end
	if AP_sortData == 1 then
		local ItemName = getglobal(name.."Name"):GetText()
		local TooltipText = AuctionProfit:TooltipItemSummary(ItemName)
		if TooltipText then
			GameTooltip:SetOwner(this, t.APwindowTooltipPosAnchor, t.APwindowTooltipPosX, t.APwindowTooltipPosY)
			GameTooltip:SetText(AP_color_green..ItemName.."\n\n"..TooltipText)
			GameTooltip:Show()
		end
	end
	if AP_sortData == 2 then
		local PlayerName = getglobal(name.."Buys"):GetText()
		local pos = string_find(PlayerName, " ", 1)
		local PlayerName = string_sub(PlayerName, 1, pos-1)
		local TooltipText = AuctionProfit:TooltipSummary(PlayerName, "APwindow")
		if TooltipText then
			GameTooltip:SetOwner(this, t.APwindowTooltipPosAnchor, t.APwindowTooltipPosX, t.APwindowTooltipPosY)
			GameTooltip:SetText(AP_color_yellow..PlayerName.."\n\n"..TooltipText)
			GameTooltip:Show()
		end
	end
	--local x2 = GetTime() self:debug("time: "..x2-x1) --BUGcheck
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:LineOnLeave(name)
	if not AP_ServerNameIndex then return end
	if not self.db.profile.settings.APwindowTooltipToggle then return end
	GameTooltip:Hide()
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:TooltipSummary(PlayerName,WhichTooltip)
	local TooltipText
	-- name loop start
	for i=1, AP_NameCount do
		if AP_NameIndex[i] == PlayerName then
			local settings = self.db.profile.settings
			local LinesCheck = settings.PlayerTooltipLines
			if WhichTooltip == "AH" then
				LinesCheck = settings.AHTooltipLines
			end
			if WhichTooltip == "APwindow" then
				LinesCheck = settings.APwindowTooltipLines
			end
			local TooltipTextTabMatrix = {}
			local MainData = APbuyer[AP_ServerNameIndex][i]
			local SubData = AP_buyerSubDataReturn(MainData)
			local BuyerMainData = AP_buyerMainDataReturn(MainData)
			local TotalProfit = AP_StrReturn(BuyerMainData,2)
			local TotalAuctions = AP_StrReturn(BuyerMainData,3)
			local TooltipTextDataM = ""
			TooltipText = AP_color_blue..L["Profit"]..": "..AP_HumanMoneyDisplay(tonumber(TotalProfit)).." "..AP_color_white.."("..TotalAuctions..")"
			if LinesCheck > 0 then
				-- buys loop start
				for j=1, AP_buyerSubDataCountReturn(MainData) do
					local al = string_len(SubData)
					local as = string_find(SubData, ":", 1)
					local as2 = string_find(SubData, "-", 1)
					local r1 = string_sub(SubData, 1, (as2-1))
					local itemname = AP_itemNameReturn(APitemName[tonumber(r1)])
					if string_len(itemname) > settings.TooltipItemNameLength then
						itemname = string_sub(itemname, 0, settings.TooltipItemNameLength).."..."
					end
					local count = AP_buyerSubDataPartBuysReturn(MainData,tonumber(r1))
					local profit = tonumber(AP_buyerSubDataPartProfitReturn(MainData,tonumber(r1)))
					-- ompf TODO
					if settings.TooltipLineDisplay == 1 then
						TooltipTextDataM =	AP_color_green..itemname.." "..AP_color_white.."("..AP_nummatrix(tostring(count), 8)..") "..AP_nummatrix(tostring(profit), 8)..
																"#-:-#"..
																AP_color_green..itemname.." "..AP_color_white.."("..count..") "..AP_HumanMoneyDisplay(profit)
						table.insert(TooltipTextTabMatrix, TooltipTextDataM)
					elseif settings.TooltipLineDisplay == 2 then
						TooltipTextDataM =	AP_color_white.."("..AP_nummatrix(tostring(count), 8)..") "..AP_color_green..itemname.." "..AP_nummatrix(tostring(profit), 8)..
																"#-:-#"..
																AP_color_white.."("..count..") "..AP_color_green..itemname.." "..AP_HumanMoneyDisplay(profit)
						table.insert(TooltipTextTabMatrix, TooltipTextDataM)
					elseif settings.TooltipLineDisplay == 3 then
						TooltipTextDataM =	AP_color_white.."("..AP_nummatrix(tostring(count), 8)..") "..AP_nummatrix(tostring(profit), 8).." "..AP_color_green..itemname..
																"#-:-#"..
																AP_color_white.."("..count..") "..AP_HumanMoneyDisplay(profit).." "..AP_color_green..itemname
						table.insert(TooltipTextTabMatrix, TooltipTextDataM)
					elseif settings.TooltipLineDisplay == 4 then
						TooltipTextDataM =	AP_nummatrix(tostring(profit), 8).." "..AP_color_green..itemname.." "..AP_color_white.."("..AP_nummatrix(tostring(count), 8)..")"..
																"#-:-#"..
																AP_HumanMoneyDisplay(profit).." "..AP_color_green..itemname.." "..AP_color_white.."("..count..")"
						table.insert(TooltipTextTabMatrix, TooltipTextDataM)
					elseif settings.TooltipLineDisplay == 5 then
						TooltipTextDataM =	AP_nummatrix(tostring(profit), 8).." "..AP_color_white.."("..AP_nummatrix(tostring(count), 8)..") "..AP_color_green..itemname..
																"#-:-#"..
																AP_HumanMoneyDisplay(profit).." "..AP_color_white.."("..count..") "..AP_color_green..itemname
						table.insert(TooltipTextTabMatrix, TooltipTextDataM)
					end
					if as == nil or as == 0 then
						break
					else
						SubData = string_sub(SubData, (as+1), al)
					end
				end
				-- buys loop end
			
				table.sort(TooltipTextTabMatrix, function(a,b) return a>b end)

				TooltipText = TooltipText.."\n"
				for k=1, #TooltipTextTabMatrix do
					local s = TooltipTextTabMatrix[k]
					local pos = string_find(s, "#-:-#", 1)
					local sub = string_sub(s, (pos+5))
					TooltipText = TooltipText..sub.."\n"
					if k == LinesCheck then
						TooltipText = TooltipText..AP_color_lightyellow.."..."..L["more"]
						break
					end
				end
			end
			TooltipTextTabMatrix = nil
			break
		end
	end
	-- name loop end
	return TooltipText
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
function AuctionProfit:TooltipItemSummary(ItemName)
	local TooltipText
	-- name loop start
	for i=1, AP_ItemCount do
		local ii = AP_ItemIndex[i]
		if string_find(APitemName[ii],ItemName.."#",1,true) then
		--if AP_itemNameReturn(APitemName[ii]) == ItemName then
			local settings = self.db.profile.settings
			local LinesCheck = settings.APwindowTooltipLines
			local TooltipTextTabMatrix = {}
			local MainData = APitemName[ii]
			local TotalProfit = AP_itemNameSubDataPartProfitReturn(MainData, AP_ServerNameIndex)
			local TotalAuctions = AP_itemNameSubDataPartBuysReturn(MainData, AP_ServerNameIndex)
			local TooltipTextDataM = ""
			TooltipText = AP_color_blue..L["Profit"]..": "..AP_HumanMoneyDisplay(tonumber(TotalProfit)).." "..AP_color_white.."("..TotalAuctions..")"

			-- item loop start
			for j=1, AP_NameCount do
				local buyer = APbuyer[AP_ServerNameIndex][j]
				
				if string_find(buyer,ii,1,true) then			
					if string_find(buyer,ii.."-",1,true) then
						local len = string_len(buyer)
						local pos = string_find(buyer,"#",1)
						local a = ":"..string_sub(buyer,pos+1,len)
						local b = ":"..ii.."-"
						if string_find(a,b,1,true) then
      	
						--if AP_buyerSubDataItemIDcheckReturn(buyer,ii) then
							local name = AP_NameIndex[j]
							local count = AP_buyerSubDataPartBuysReturn(buyer,ii)
							local profit = tonumber(AP_buyerSubDataPartProfitReturn(buyer,ii))
							-- ompf TODO
							if settings.TooltipLineDisplay == 1 then
								TooltipTextDataM =	AP_color_yellow..name.." "..AP_color_white.."("..AP_nummatrix(tostring(count), 8)..") "..AP_nummatrix(tostring(profit), 8)..
																		"#-:-#"..
																		AP_color_yellow..name.." "..AP_color_white.."("..count..") "..AP_HumanMoneyDisplay(profit)
								table.insert(TooltipTextTabMatrix, TooltipTextDataM)
							elseif settings.TooltipLineDisplay == 2 then
								TooltipTextDataM =	AP_color_white.."("..AP_nummatrix(tostring(count), 8)..") "..AP_color_yellow..name.." "..AP_nummatrix(tostring(profit), 8)..
																		"#-:-#"..
																		AP_color_white.."("..count..") "..AP_color_yellow..name.." "..AP_HumanMoneyDisplay(profit)
								table.insert(TooltipTextTabMatrix, TooltipTextDataM)
							elseif settings.TooltipLineDisplay == 3 then
								TooltipTextDataM =	AP_color_white.."("..AP_nummatrix(tostring(count), 8)..") "..AP_nummatrix(tostring(profit), 8).." "..AP_color_yellow..name..
																		"#-:-#"..
																		AP_color_white.."("..count..") "..AP_HumanMoneyDisplay(profit).." "..AP_color_yellow..name
								table.insert(TooltipTextTabMatrix, TooltipTextDataM)
							elseif settings.TooltipLineDisplay == 4 then
								TooltipTextDataM =	AP_nummatrix(tostring(profit), 8).." "..AP_color_yellow..name.." "..AP_color_white.."("..AP_nummatrix(tostring(count), 8)..")"..
																		"#-:-#"..
																		AP_HumanMoneyDisplay(profit).." "..AP_color_yellow..name.." "..AP_color_white.."("..count..")"
								table.insert(TooltipTextTabMatrix, TooltipTextDataM)
							elseif settings.TooltipLineDisplay == 5 then
								TooltipTextDataM =	AP_nummatrix(tostring(profit), 8).." "..AP_color_white.."("..AP_nummatrix(tostring(count), 8)..") "..AP_color_yellow..name..
																		"#-:-#"..
																		AP_HumanMoneyDisplay(profit).." "..AP_color_white.."("..count..") "..AP_color_yellow..name
								table.insert(TooltipTextTabMatrix, TooltipTextDataM)
							end
						end
      	
					end
				end

			end
			-- item loop end
			
			table.sort(TooltipTextTabMatrix, function(a,b) return a>b end)

			TooltipText = TooltipText.."\n"
			for k=1, #TooltipTextTabMatrix do
				local s = TooltipTextTabMatrix[k]
				local pos = string_find(s, "#-:-#", 1)
				local sub = string_sub(s, (pos+5))
				TooltipText = TooltipText..sub.."\n"
				if k == LinesCheck then
					TooltipText = TooltipText..AP_color_lightyellow.."..."..L["more"]
					break
				end
			end
			TooltipTextTabMatrix = nil
			break
		end
	end
	-- name loop end
	return TooltipText
end
-- -----------------------------------------------------------------------------



-- -----------------------------------------------------------------------------
AP_HumanMoneyDisplay = function(money)
	local GoldColor = "|cffffd100"
	local SilverColor = "|cffe6e6e6"
	local CopperColor = "|cffc8602c"
	local Gold = floor(money/10000)
	local Silver = floor((money-Gold*10000)/100)
	local Copper = money-Gold*10000-Silver*100
	local m
	if money < 100 then
		m = CopperColor..Copper..L["c"]
	end
	if money >= 100 and money < 10000 then
		if Copper < 10 then Copper = "0"..Copper end
		m = SilverColor..Silver..L["s"].." "..CopperColor..Copper..L["c"]
	end
	if money >= 10000 then
		if Copper < 10 then Copper = "0"..Copper end
		if Silver < 10 then Silver = "0"..Silver end
		m = GoldColor..Gold..L["g"].." "..SilverColor..Silver..L["s"].." "..CopperColor..Copper..L["c"]
	end
	return m
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_nummatrix
--
-- parameter: x = string | y = number (longest string lenght)
-- example: x = "193" | y = 8
-- return: string
--         (example: "00000bjd")
--
-- matrix: x0123456789
--         0abcdefghij
---
AP_nummatrix = function(x, y)
	local xl = string_len(x)
	local xd
	x = string_gsub(x, "0", "a")
	x = string_gsub(x, "1", "b")
	x = string_gsub(x, "2", "c")
	x = string_gsub(x, "3", "d")
	x = string_gsub(x, "4", "e")
	x = string_gsub(x, "5", "f")
	x = string_gsub(x, "6", "g")
	x = string_gsub(x, "7", "h")
	x = string_gsub(x, "8", "i")
	x = string_gsub(x, "9", "j")
	if xl < y then
		xd = y - xl
		for i=1, xd do		
			x = "0"..x
		end
	end
	return x
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_StrReturn
--
-- parameter: str = string | part = number
-- example: str = "PlayerName:211375:8" | part = 2
-- return: string
--         (example: "211375")
--
-- xxxxxxxxxx:xxxxxx:x
-- 1          2      3
-- PlayerName:211375:8
---
AP_StrReturn = function(str, part)
	local part1, part2, part3 = string_match(str, "(.+):(.+):(.+)")
	if part == 1 then return part1 end
	if part == 2 then return part2 end
	if part == 3 then return part3 end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_buyerNameReturn
--
-- parameter: x = string
-- example: x = "PlayerName:211375:8#15-129675-4:20-13300-1:77-31350-1:42-22800-1:10-14250-1" 
-- return: string
--         (example: "PlayerName")
---
AP_buyerNameReturn = function(x)
	local pos = string_find(x, ":", 1)
	local str = string_sub(x, 1, pos-1)
	return str
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_buyerMainDataReturn
--
-- parameter: x = string
-- example: x = "PlayerName:211375:8#15-129675-4:20-13300-1:77-31350-1:42-22800-1:10-14250-1"
-- return: string
--         (example: "PlayerName:211375:8")
---
AP_buyerMainDataReturn = function(x)
	local pos = string_find(x, "#", 1)
	local str = string_sub(x, 1, pos-1)
	return str
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_buyerSubDataReturn
--
-- parameter: x = string
-- example: x = "PlayerName:211375:8#15-129675-4:20-13300-1:77-31350-1:42-22800-1:10-14250-1"
-- return: string
--         (example: "15-129675-4:20-13300-1:77-31350-1:42-22800-1:10-14250-1")
---
AP_buyerSubDataReturn = function(x)
	local len = string_len(x)
	local pos = string_find(x, "#", 1)
	local str = string_sub(x, pos+1, len)
	return str
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_buyerSubDataCountReturn
--
-- parameter: x = string
-- example: x = "PlayerName:211375:8#15-129675-4:20-13300-1:77-31350-1:42-22800-1:10-14250-1"
-- return: number
--         n (example: return 5 for 5 SubData entries: 1="15-129675-4"  2="20-13300-1"  3="77-31350-1"  4="42-22800-1"  5="10-14250-1")
---
AP_buyerSubDataCountReturn = function(x)
	local a, b = string_gsub(AP_buyerSubDataReturn(x), ":", ":")
	return (b+1)
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_buyerSubDataItemIDcheckReturn
--
-- parameter: x = string | y = number
-- example: x = "PlayerName:211375:8#15-129675-4:20-13300-1:77-31350-1:42-22800-1:10-14250-1"
--          y = itemID
-- return: number
--         0 = no itemID avaiable  1 = itemID availabe
---
AP_buyerSubDataItemIDcheckReturn = function(x, y)
	local len = string_len(x)
	local pos = string_find(x,"#",1)
	local a = ":"..string_sub(x,pos+1,len)
	local b = ":"..y.."-"
	if string_find(a,b,1,true) then
		return true
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_buyerSubDataPartReturn
--
-- parameter: x = string | y = number
-- example: x = "PlayerName:211375:8#15-129675-4:20-13300-1:77-31350-1:42-22800-1:10-14250-1"
--          y = itemID
-- return: string
--         (example: part from y (itemID) --> y=77 return:"77-31350-1")
---
AP_buyerSubDataPartReturn = function(x, y)
	local a = ":"..AP_buyerSubDataReturn(x)..":"
	local b = ":"..tostring(y).."-"
	local pos = string_find(a, b, 1, true)
	local len = string_len(a)
	local r = string_sub(a, pos+1, len)
	local rpos = string_find(r, ":", 1)
	local part = string_sub(r, 1, rpos-1)
	return part
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_buyerSubDataPartProfitReturn
--
-- parameter: x = string | y = number
-- example: x = "PlayerName:211375:8#15-129675-4:20-13300-1:77-31350-1:42-22800-1:10-14250-1"
--          y = itemID
-- return: string
--         (example: profit from y (itemID) --> y=77 return:"31350")
---
AP_buyerSubDataPartProfitReturn = function(x, y)
	local a = AP_buyerSubDataPartReturn(x, y)
	local l = string_len(a)
	local pos = string_find(a, "-", 1, true)
	local pos2 = string_find(a, "-", (l*-1)+pos)
	local r = string_sub(a, pos+1, pos2-1)
	return r
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_buyerSubDataPartBuysReturn
--
-- parameter: x = string | y = number
-- example: x = "PlayerName:211375:8#15-129675-4:20-13300-1:77-31350-1:42-22800-1:10-14250-1"
--          y = itemID
-- return: string
--         (example: buys from y (itemID) --> y=15 return:"4")
---
AP_buyerSubDataPartBuysReturn = function(x, y)
	local a = AP_buyerSubDataPartReturn(x, y)
	local l = string_len(a)
	local pos = string_find(a, "-", 1, true)
	local pos2 = string_find(a, "-", (l*-1)+pos)
	local r = string_sub(a, pos2+1, l)
	return r
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_buyerSubDataPartReplaceReturn
--
-- parameter: x = string | y = string (replace) | z = string (new)
-- example: x = "PlayerName:211375:8#15-129675-4:20-13300-1:77-31350-1:42-22800-1:10-14250-1"
--          y = "15-129675-4"
--          z = "15-176483-5"
-- return: string
--         (example: old string x      "15-129675-4:20-13300-1:77-31350-1:42-22800-1:10-14250-1")
--         (         new return string "15-176483-5:20-13300-1:77-31350-1:42-22800-1:10-14250-1")
---
AP_buyerSubDataPartReplaceReturn = function(x, y, z)
	local x1 = AP_buyerSubDataReturn(x)
	local y1 = string_gsub(y, "-", "%%-")
	local r = string_gsub(x1, y1, z)
	return r
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_itemNameReturn
--
-- parameter: x = string
-- example: x = "Begrenzter Unverwundbarkeitstrank#1-83500-6"
-- return: string
--         (example: return "Begrenzter Unverwundbarkeitstrank")
---
AP_itemNameReturn = function(x)
	local pos = string_find(x, "#", 1)
	local str = string_sub(x, 1, pos-1)
	return str
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_itemNameSubDataReturn
--
-- parameter: x = string
-- example: x = "Begrenzter Unverwundbarkeitstrank#1-83500-6:2-56782-4"
-- return: string
--         (example: return "1-83500-6:2-56782-4")
---
AP_itemNameSubDataReturn = function(x)
	local len = string_len(x)
	local pos = string_find(x, "#", 1)
	local str = string_sub(x, pos+1, len)
	return str
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_itemNameServerCheckReturn
--
-- parameter: x = string | y = number (serverID)
-- example: x = "Begrenzter Unverwundbarkeitstrank#1-83500-6:2-56782-4"
--          y = 2
-- return: number 
--         (example: return 1 - 0 = serverID not exists  1 = serverID exists)
---
AP_itemNameServerCheckReturn = function(x, y)
	local a = ":"..AP_itemNameSubDataReturn(x)..":"
	local b = ":"..tostring(y).."-"
	if string_find(a, b, 1, true) then
		return true
	end
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_itemNameSubDataPartReturn
--
-- parameter: x = string | y = number (serverID)
-- example: x = "Begrenzter Unverwundbarkeitstrank#1-83500-6:2-56782-4"
--          y = 2
-- return: string
--         (example: part von y (serverID) --> y=2 return:"2-56782-4")
---
AP_itemNameSubDataPartReturn = function(x, y)
	local a = ":"..AP_itemNameSubDataReturn(x)..":" -- a = :1-83500-6:2-56782-4:
	local b = ":"..tostring(y).."-"
	local pos = string_find(a, b, 1, true)
	local len = string_len(a)
	local r = string_sub(a, pos+1, len)
	local rpos = string_find(r, ":", 1)
	local part = string_sub(r, 1, rpos-1)
	return part
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_itemNameSubDataPartProfitReturn
--
-- parameter: x = string | y = number (serverID)
-- example: x = "Begrenzter Unverwundbarkeitstrank#1-83500-6:2-56782-4"
--          y = 2 
-- return: string
--         (example: profit von y (serverID) --> y=2 return:"56782")
---
AP_itemNameSubDataPartProfitReturn = function(x, y)
	local a = AP_itemNameSubDataPartReturn(x, y)
	local l = string_len(a)
	local pos = string_find(a, "-", 1, true)
	local pos2 = string_find(a, "-", (l*-1)+pos)
	local r = string_sub(a, pos+1, pos2-1)
	return r
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_itemNameSubDataPartBuysReturn
--
-- parameter: x = string | y = number (serverID)
-- example: x = "Begrenzter Unverwundbarkeitstrank#1-83500-6:2-56782-4"
--          y = 2 
-- return: string
--         (example: buys von y (serverID) --> y=2 return:"4")
---
AP_itemNameSubDataPartBuysReturn = function(x, y)
	local a = AP_itemNameSubDataPartReturn(x, y)
	local l = string_len(a)
	local pos = string_find(a, "-", 1, true)
	local pos2 = string_find(a, "-", (l*-1)+pos)
	local r = string_sub(a, pos2+1, l)
	return r
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_itemNameSubDataPartReplaceReturn
--
-- parameter: x = string | y = string (replace) | z = string (new)
-- example: x = "Begrenzter Unverwundbarkeitstrank#1-83500-6:2-56782-4"
--          y = "1-83500-6"
--          z = "1-117540-7"
-- return: string
--         (example: old string x      "1-83500-6:2-56782-4")
--         (example: new return string "1-117540-7:2-56782-4")
---
AP_itemNameSubDataPartReplaceReturn = function(x, y, z)
	local x1 = AP_itemNameSubDataReturn(x)
	local y1 = string_gsub(y, "-", "%%-")
	local r = string_gsub(x1, y1, z)
	return r
end
-- -----------------------------------------------------------------------------

-- -----------------------------------------------------------------------------
-- AP_lastAuctionsReturn
--
-- parameter: x = string (date#ItemID:Profit:PlayerNameID) | s = number (serverID)
-- example: date = date("%y%m%d %H%M")
--          x = "071126 1922#23:11400:460"
--          s = 1
-- returns: string
--          (example: "|cffffffff071126 1922|r someitem:11400:somename |cffffffff(count)")
--
-- example: x = "date#ItemID:Profit:PlayerNameID"
--          s = 1
--          return: "date ItemName:Profit:PlayerName (count)"
---
AP_lastAuctionsReturn = function(x, s)
	local pos = string_find(x, "#", 1)
	local xdate = string_sub(x, 1, pos-1)

	local x = string_sub(x, pos+1)

	local a1 = AP_StrReturn(x, 1) -- return itemID
	local a2 = AP_StrReturn(x, 2) -- return profit
	local a3 = AP_StrReturn(x, 3) -- return playerNameID

	local Buyer = APbuyer[s][tonumber(a3)]
	local MainData = AP_buyerMainDataReturn(Buyer)
	local a3buys = AP_StrReturn(MainData, 3)
	local a3profit = AP_StrReturn(MainData, 2)

	local a1r = AP_itemNameReturn(APitemName[tonumber(a1)]) -- return itemName
	local a3r = AP_buyerNameReturn(Buyer) -- return playerName

	local r = AP_color_white..xdate.."|r "..a1r..":"..tostring(a2)..":"..a3r.." "..AP_color_white.."("..tostring(a3buys)..")"
	-- AuctionProfit:debug("AP_lastAuctionsReturn: "..r) -- BUGcheck
	return r
end
-- -----------------------------------------------------------------------------
